package com.hdmp.wework.handler;

import com.hdmp.wework.builder.TextBuilder;
import com.hdmp.wework.entity.GryxWechatGzzhEntity;
import com.hdmp.wework.entity.GryxWechatKeywordsEntity;
import com.hdmp.wework.entity.GryxWechatTokenEntity;
import com.hdmp.wework.mapper.WechatGzzhMapper;
import com.hdmp.wework.mapper.WechatKeywordsMapper;
import com.hdmp.wework.mapper.WechatTokenMapper;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class MsgHandler extends AbstractHandler {

    @Autowired
    @Lazy
    WechatGzzhMapper wechatGzzhMapper;
    @Autowired
    WechatTokenMapper tokenMapper;
    @Autowired
    WechatKeywordsMapper keywordsMapper;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                     Map<String, Object> context, WxMpService wxMpService,
                                     WxSessionManager sessionManager){
        if(!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)){
            //todo 可以选择将消息保存到本地
        }


        try {
            if (StringUtils.startsWithAny(wxMessage.getContent())) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(wxMessage.getToUser());

        System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
        GryxWechatKeywordsEntity keywordsEntity = keywordsMapper.queryKeywordByAccountidAndKeywords(wxMessage.getToUser(), wxMessage.getContent());
        System.out.println(keywordsEntity);
        System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
        String content = "收到信息内容：";
        if(keywordsEntity == null){
            content = "欢迎您使用微信公众号";
        }else{
            content = keywordsEntity.getContent();
        }
        return new TextBuilder().build(content, wxMessage, wxMpService);
    }
}